// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成
package com.fowo.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.common.model.IdListPo;
import com.fowo.api.common.model.IdPo;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.R;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.WmsOrder;
import com.fowo.api.model.wms.order.WmsOrderImportPo;
import com.fowo.api.model.wms.order.WmsOrderItemVo;
import com.fowo.api.model.wms.order.WmsOrderSearchParamPo;
import com.fowo.api.model.wms.order.WmsOrderVo;
import com.fowo.api.service.WmsOrderService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.user.model.JwtUserInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StreamUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "销售出库单(wms)")
@RequestMapping("/api/wms-order")
@RestController
public class WmsOrderController {

  @Resource
  private WmsOrderService service;

  @Operation(summary = "查询结果")
  @GetMapping
  public R<List<WmsOrderItemVo>> search(WmsOrderSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.search(search));
  }

  @Operation(summary = "快速查询选项(有缓存)")
  @GetMapping("options")
  public R<List<OptionItem<WmsOrderItemVo>>> searchOptions(
    WmsOrderSearchParamPo search
  ) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.searchOptions(search));
  }

  @Operation(summary = "查询最后更新时间")
  @GetMapping("lastUpdateTime")
  public R<Date> searchLastUpdateTime(WmsOrderSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.searchLastUpdateTime(search));
  }

  @Operation(summary = "获取分页查询结果")
  @GetMapping("page")
  public R<Page<WmsOrderItemVo>> getPage(WmsOrderSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.pageSearch(search));
  }

  @Operation(summary = "查询是否后台下载")
  @GetMapping("getBackgroundExportFlag")
  public R<Boolean> getBackgroundExportFlag(WmsOrderSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.getBackgroundExportFlag(search));
  }

  @Operation(summary = "获取详情")
  @GetMapping("{id}")
  public R<WmsOrderVo> getVoById(@PathVariable Long id) {
    return R.data(() -> service.getVoById(id));
  }

  @Operation(summary = "获取系统单号相关的编号列表")
  @GetMapping("order-number/{texts}/ids")
  public R<List<Long>> getIdsByOrderNumber(@PathVariable String texts) {
    List<String> nameList = Arrays
      .stream(texts.split(","))
      .collect(Collectors.toList());
    return R.data(() -> service.getIdsByOrderNumber(nameList));
  }

  @Operation(summary = "获取编号相关的系统单号列表")
  @GetMapping("order-number/{ids}")
  public R<List<String>> getVoById(@PathVariable String ids) {
    List<Long> idList = Arrays
      .asList(ids.split(","))
      .stream()
      .map(Long::valueOf)
      .collect(Collectors.toList());
    return R.data(() -> service.getOrderNumberByIds(idList));
  }

  @PreAuthorize("@am.canAccess('wmsOrderCreate')")
  @Operation(summary = "新增")
  @PostMapping
  public R<Long> create(@Validated @RequestBody WmsOrderVo model) {
    return R.data(() -> service.create(model));
  }

  @PreAuthorize("@am.canAccess('wmsOrderEdit')")
  @Operation(summary = "更新")
  @PutMapping
  public R update(@RequestBody WmsOrderVo model) {
    return R.run(() -> service.update(model));
  }

  @PreAuthorize("@am.canAccess('wmsOrderEdit')")
  @Operation(summary = "编辑更新")
  @PutMapping("edit")
  public R updateForEdit(@RequestBody WmsOrderVo model) {
    return R.run(() -> service.updateForEdit(model));
  }

  @PreAuthorize("@am.canAccess('wmsOrderDelete')")
  @Operation(summary = "删除")
  @DeleteMapping("{id}")
  public R delete(@PathVariable Long id) {
    return R.run(() -> service.delete(id));
  }

  @PreAuthorize("@am.canAccess('wmsOrderDelete')")
  @Operation(summary = "批量删除")
  @DeleteMapping("batch")
  public R batchDelete(@RequestBody IdListPo po) {
    return R.run(() -> service.batchDelete(po.getIds()));
  }

  @PreAuthorize("@am.canAccess('wmsOrderImport')")
  @Operation(summary = "导入预览")
  @PostMapping("import-preview")
  public R<List<ImportRow<WmsOrderImportPo>>> importPreview(
    @RequestBody SysFile sysFile,
    @RequestParam(name = "template", required = false) Long templateId,
    @RequestParam(
      name = "allowOverrides",
      defaultValue = "false"
    ) boolean allowOverrides
  ) {
    return R.data(() ->
      service.importPreview(sysFile, templateId, allowOverrides)
    );
  }

  @PreAuthorize("@am.canAccess('wmsOrderImport')")
  @Operation(summary = "完成导入")
  @PostMapping("import-done")
  public R importDone(
    @RequestBody List<ImportRow<WmsOrderImportPo>> rows,
    @RequestParam(name = "template", required = false) Long templateId
  ) {
    return R.run(() -> service.importDone(rows, templateId));
  }

  @Operation(summary = "下载导入模版")
  @GetMapping("import/template")
  public void downloadImportTemplate(HttpServletResponse response)
    throws IOException {
    ResponseUtils.setAttachmentFileName(
      response,
      "销售出库单(wms)导入模版.xlsx"
    );
    InputStream inputStream = new ClassPathResource("templates/WmsOrder.xlsx")
      .getInputStream();
    StreamUtils.copy(inputStream, response.getOutputStream());
  }

  @Operation(summary = "导出")
  @GetMapping("export")
  @PreAuthorize("@am.canAccess('wmsOrderExport')")
  public void export(
    @RequestParam(name = "template", required = false) Long templateId,
    WmsOrderSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    service.export(templateId, search, response);
  }

  @PreAuthorize("@am.canAccess('wmsOrderSalesOutWarehouse')")
  @Operation(summary = "销售出库")
  @PostMapping("salesOutWarehouse")
  public R salesOutWarehouse(@RequestBody IdListPo idListPo) {
    return R.run(() -> service.salesOutWarehouse(idListPo.getIds()));
  }

  @PreAuthorize("@am.canAccess('wmsOrderCancelLocksInventory')")
  @Operation(summary = "订单(取消锁库存_即时)")
  @PostMapping("cancelLocksInventory")
  public R cancelLocksInventory(@RequestBody IdPo idPo) {
    return R.run(() -> service.cancelLocksInventory(idPo.getId()));
  }

  @PreAuthorize("@am.canAccess('wmsOrderCancelLockpInventory')")
  @Operation(summary = "订单（取消锁库存_仓位）")
  @PostMapping("cancelLockpInventory")
  public R cancelLockpInventory(@RequestBody IdPo idPo) {
    return R.run(() -> service.cancelLockpInventory(idPo.getId()));
  }

  @PreAuthorize("@am.canAccess('wmsOrderLockStockOut')")
  @Operation(summary = "订单（从锁定库存出库）")
  @PostMapping("lockStockOut")
  public R lockStockOut(@RequestBody IdPo idPo) {
    return R.run(() -> service.lockStockOut(idPo.getId()));
  }

  @PreAuthorize("@am.canAccess('wmsOrderLocksInventory')")
  @Operation(summary = "订单锁库存（锁库存_即时）")
  @PostMapping("locksInventory")
  public R locksInventory(@RequestBody IdPo idPo) {
    return R.run(() -> service.locksInventory(idPo.getId()));
  }

  @PreAuthorize("@am.canAccess('wmsOrderLockpInventory')")
  @Operation(summary = "订单锁库存（锁库存_仓位）")
  @PostMapping("lockpInventory")
  public R lockpInventory(@RequestBody IdPo idPo) {
    return R.run(() -> service.lockpInventory(idPo.getId()));
  }

  @PreAuthorize("@am.canAccess('wmsOrderCancelpWarehousing')")
  @Operation(summary = "撤销到锁定")
  @PostMapping("cancelpWarehousing")
  public R cancelpWarehousing(@RequestBody IdPo idPo) {
    return R.run(() -> service.cancelpWarehousing(idPo.getId()));
  }

  @PreAuthorize("@am.canAccess('wmsOrderSyncWms')")
  @Operation(summary = "同步当天数据")
  @PostMapping("syncWms")
  public R syncWms() {
    return R.run(() -> service.syncWms());
  }

  @PreAuthorize("@am.canAccess('wmsOrderCancelWarehousing')")
  @Operation(summary = "撤销库存")
  @PostMapping("cancelWarehousing")
  public R cancelWarehousing(@RequestBody IdPo idPo) {
    return R.run(() -> service.cancelWarehousing(idPo.getId()));
  }

  @Operation(summary = "根据时间同步领星销售出库单表单确定操作")
  @PostMapping("sync-date-wms/confirm")
  public R<?> syncDateWmsConfirm(@RequestBody JSONObject data) {
    return R.run(() -> service.syncDateWmsConfirm(data));
  }

  @PreAuthorize("@am.canAccess('wmsOrderBatchStockOut')")
  @Operation(summary = "批量出库")
  @PostMapping("batchStockOut")
  public R batchStockOut(@RequestBody IdListPo po) {
    return R.run(() -> service.batchStockOut(po.getIds()));
  }

  @PreAuthorize("@am.canAccess('wmsOrderSubInventory')")
  @Operation(summary = "扣库存")
  @PostMapping("subInventory")
  public R subInventory(@RequestBody IdPo idPo) {
    return R.run(() -> service.subInventory(idPo.getId()));
  }

  @PreAuthorize("@am.canAccess('wmsOrderStockOut')")
  @Operation(summary = "直接扣减库存")
  @PostMapping("stockOut")
  public R stockOut(@RequestBody IdPo idPo) {
    return R.run(() -> service.stockOut(idPo.getId()));
  }

  /**
   * 视图选项卡标题上显示计数
   */
  @Operation(summary = "视图选项卡标题上显示计数")
  @GetMapping("getTabHeaderShowTotal")
  public R<Map> getTabHeaderShowTotal() {
    return R.data(() -> service.getTabHeaderShowTotal());
  }

  @Operation(summary = "销售出库单")
  @GetMapping("wms-order")
  public R<List<WmsOrderItemVo>> wmsOrder(WmsOrderSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(() -> service.wmsOrder(search));
  }

  @Operation(summary = "销售出库单分页")
  @GetMapping("wms-orderPage")
  public R<Page<WmsOrderItemVo>> wmsOrderPage(WmsOrderSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(() -> service.wmsOrderPage(search));
  }

  @Operation(summary = "销售出库单最后更新时间")
  @GetMapping("wms-orderLastUpdateTime")
  public R<Date> wmsOrderLastUpdateTime(WmsOrderSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(() -> service.wmsOrderLastUpdateTime(search));
  }
}
